package com.lyh.hkcloud.module.m1300026;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.*;
import com.lyh.hkcloud.R;
import com.lyh.hkcloud.activity.HomeActivity;
import com.lyh.hkcloud.base.BaseActivity;
import com.lyh.hkcloud.constants.BusinessConstants;
import com.lyh.hkcloud.constants.HttpUrlComstants;
import com.lyh.hkcloud.module.common.ActivityUtil;
import com.lyh.hkcloud.module.m1300026.adapter.ListViewAdapter;
import com.lyh.hkcloud.module.m1300026.service.Service;
import com.lyh.hkcloud.util.base.JsonUtil;
import com.lyh.hkcloud.util.base.SaveData;
import com.lyh.hkcloud.util.base.StringUtils;
import com.lyh.hkcloud.util.base.ToastUtils;
import com.lyh.hkcloud.util.http.listener.json.JsonFailuredListener;
import com.lyh.hkcloud.util.http.listener.json.JsonSuccessListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

/**
 * @author: zhongfan
 * @program: hkCloud
 * @description:盘点管理
 * @company—date: 利元数据 2022-02-16 10:04
 **/
public class IndexActivity extends BaseActivity implements View.OnClickListener{

    private ImageView go_back;
    private Button bt_resetting;
    private Button bt_query;
    private Spinner sp_bill_statename;
    private EditText et_bill_number;
    private ListView lvAssets;

    private List<HashMap<String,Object>> dataList = new ArrayList<>();
    private ListViewAdapter listViewAdapter;
    private Integer receiverFocusEvent = 0;
    //盘点单状态
    List<String> stateList = new ArrayList<>();

    private Service service;

    @Override
    protected void onBeginInit() {
        service = new Service(this);
    }

    @Override
    protected void onSubmit() {
        bt_query.setEnabled(false);
        this.queryInventory();
        bt_query.setEnabled(true);
    }

    @Override
    protected Activity getActivity() {
        return this;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_1300026;
    }

    @Override
    protected int getSubmitResId() {
        return R.id.bt_query;
    }

    @Override
    protected int getClearResId() {
        return R.id.bt_resetting;
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        registerReceiver(receiver, Filter());
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unregisterReceiver(receiver);
    }

    private static IntentFilter Filter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BusinessConstants.ACTION);
        return intentFilter;
    }


    @Override
    protected void onClear(View... ignores) {
        //super.onClear(ignores);
//        dataList.clear();
//        updateAssetList();
        et_bill_number.setText(BusinessConstants.DOCUMENT_NO);
        sp_bill_statename.setSelection(0);

        Log.v("clear**","清空**");
    }


    @Override
    protected void initView() {
        go_back = findViewById(R.id.go_back);
        bt_resetting=findViewById(R.id.bt_resetting);
        bt_query=findViewById(R.id.bt_query);
        sp_bill_statename=findViewById(R.id.sp_bill_statename);
        et_bill_number=findViewById(R.id.et_bill_number);
        lvAssets=findViewById(R.id.lv_assets);
        getSupportActionBar().hide();
    }

    //时间分发方法重写
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //如果是点击事件，获取点击的view，并判断是否要收起键盘
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //获取目前得到焦点的view
            View v = getCurrentFocus();
            //判断是否要收起并进行处理
            if (ActivityUtil.isShouldHideKeyboard(v, ev)) {
                ActivityUtil.hideKeyboard(v.getWindowToken(),this,et_bill_number);
            }
        }
        //这个是activity的事件分发，一定要有，不然就不会有任何的点击事件了
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void initEvent() {

        go_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(IndexActivity.this, HomeActivity.class);
                IndexActivity.this.startActivity(intent);
            }
        });

        et_bill_number.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    if (BusinessConstants.DOCUMENT_NO.equals(String.valueOf(et_bill_number.getText()))) {
                        et_bill_number.setText("");
                    }
                    receiverFocusEvent = 1;
                }else{
                    if ( et_bill_number.getText() == null || "".equals(String.valueOf(et_bill_number.getText()))) {
                        et_bill_number.setText(BusinessConstants.DOCUMENT_NO);
                    }
                    receiverFocusEvent = 0;
                }
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        listViewAdapter = new ListViewAdapter(this, dataList);
        lvAssets.setAdapter(listViewAdapter);
/*        lvAssets.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Map<String,Object>data=dataList.get(position);
                Intent intent =new Intent(IndexActivity.this, com.lyh.hkcloud.module.m1300027.IndexActivity.class);
                intent.putExtra(BusinessConstants.BILL_NUMBER,data.get(BusinessConstants.BILL_NUMBER).toString());
                IndexActivity.this.startActivity(intent);
            }
        });*/
        //盘点单状态
        stateList.add("已创建");
        stateList.add("已过账");
        stateList.add("盘点完成");
        initSpinner(stateList, sp_bill_statename, null);

        this.queryInventory();
    }

    /**
     * 扫描 接收者
     *
     * @author: zhongfan
     * @Date 2022/2/15 21:00
     **/
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String msg = intent.getStringExtra(BusinessConstants.TAG);
            Log.i(BusinessConstants.TAG, msg);

            JSONObject jsonObject = new JSONObject();

            try {
                jsonObject.put("facardcode", msg);
                jsonObject.put("psncode", msg);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            //添加接收人
            if (receiverFocusEvent == 1) {
                et_bill_number.setText(msg);
            }
        }
    };

    /**
     * 给下拉框赋值
     *
     * @param starArray            数据集合
     * @param spinner              下拉框
     * @param specifyDefaultValues 默认选中值
     * @return void
     * @author: 黄斌成
     * @Date 2022/2/18 14:34
     **/
    private void initSpinner(List<String> starArray, Spinner spinner, String specifyDefaultValues) {
        starArray.add(0,BusinessConstants.PLEASE_SELECT);
        //声明一个下拉列表的数组适配器
        ArrayAdapter<String> starAdapter = new ArrayAdapter<>(IndexActivity.this, R.layout.item_select, starArray);

        //设置数组适配器的布局样式
        starAdapter.setDropDownViewResource(R.layout.item_dropdown);

        //设置下拉框的标题，不设置就没有难看的标题了
        spinner.setPrompt("请选择行星");
        //设置下拉框的数组适配器
        spinner.setAdapter(starAdapter);
        //设置下拉框默认的显示第一项
        if (StringUtils.isNotEmpty(specifyDefaultValues) && starArray.indexOf(specifyDefaultValues) != -1) {
            spinner.setSelection(starArray.indexOf(specifyDefaultValues));
        } else {
            spinner.setSelection(0);
        }
        starArray.indexOf(specifyDefaultValues);
        spinner.setSelection(0);
        //给下拉框设置选择监听器，一旦用户选中某一项，就触发监听器的onItemSelected方法
        //spinner.setOnItemSelectedListener(new MySelectedListener(starArray, key));
        //Log.v("starArry", starArray.toString());
    }

    /**
     * @Description 根据当前登录用户查询有权限的盘点列表.
     * @param
     * @return
     * @Date 2022/2/19 15:00
     * @author 黄斌成
    **/
    private void queryInventory(){


        dataList.clear();
        Map<String, Object> inMap = new HashMap<>();

        List<String> deptIdList = new ArrayList<>();
        List<String> roleIdList = new ArrayList<>();


        String userid = SaveData.getString(this, "userid");
        String deptList = SaveData.getString(this, "deptList");
        String roleList = SaveData.getString(this, "roleList");

        if (et_bill_number.getText() != null && !BusinessConstants.DOCUMENT_NO.equals(et_bill_number.getText().toString())) {
            inMap.put("billnumber", et_bill_number.getText());
        }

        if (sp_bill_statename.getSelectedItemPosition() != -1 && !BusinessConstants.PLEASE_SELECT.equals(stateList.get(sp_bill_statename.getSelectedItemPosition()))) {
            inMap.put("billstatename", stateList.get(sp_bill_statename.getSelectedItemPosition()));
        }

        try {

            JSONArray deptArray = new JSONArray(deptList);
            JSONArray roleArray = new JSONArray(roleList);

            for (int i = 0; i < deptArray.length(); i++) {
                String fullId = deptArray.optJSONObject(i).getString("fullId");
                String[] split = fullId.split(",");
                deptIdList.addAll(Arrays.asList(split));
            }
            // userid  用户id     roleList  角色ids    deptList  部门ids
            for (int i = 0; i <roleArray.length();  i++) {
                String id = roleArray.optJSONObject(i).getString("id");
                roleIdList.add(id);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        inMap.put("userid",userid);
        inMap.put("roleList",roleIdList);
        inMap.put("deptList",deptIdList);

        service.post(JsonUtil.toJSONObject(inMap), HttpUrlComstants.QUERY_INVENTORY_LIST, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {

                try {
                    JSONArray dataArray = response.optJSONArray("data");
                    JSONObject jsonObject = dataArray.getJSONObject(0);
                    JSONObject resultlist1 = jsonObject.getJSONObject("resultlist");
                    JSONArray result = resultlist1.getJSONArray("resultData");
                    if (result == null ||result.length() == 0) {
                        ToastUtils.makeText(IndexActivity.this, "查询数据为空", ToastUtils.LENGTH_SHORT).show();
                    }
                    for(int i=0;i<result.length();i++){
                        HashMap<String,Object>data=new HashMap<>(6);
                        data.put("billnumber",result.getJSONObject(i).get("billnumber"));
                        data.put("billstatename",result.getJSONObject(i).get("billstatename"));
                        data.put("createtime",result.getJSONObject(i).get("createtime"));
                        data.put("billstateid",result.getJSONObject(i).get("billstateid"));
                        data.put("billtype",result.getJSONObject(i).get("billtype"));
                        data.put(BusinessConstants.ID,result.getJSONObject(i).get(BusinessConstants.ID));
                        dataList.add(data);
                    }
                    updateAssetList();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error",response.optString("message"));
                ToastUtils.makeText(IndexActivity.this, response.optString("message"), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    private void updateAssetList() {
        listViewAdapter = new ListViewAdapter(IndexActivity.this, dataList);
        lvAssets.setAdapter(listViewAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.go_back:
                Intent intent = new Intent(IndexActivity.this, HomeActivity.class);
                IndexActivity.this.startActivity(intent);
                break;
            case R.id.et_bill_number:

                et_bill_number.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if(hasFocus){
                            et_bill_number.setText("");
                            receiverFocusEvent = 1;
                        }else{
                            if ( et_bill_number.getText() == null ||BusinessConstants.SCAN_WHEN_SELECTED.equals(et_bill_number.getText().toString())) {
                                et_bill_number.setText(BusinessConstants.SCAN_WHEN_SELECTED);
                            }
                            receiverFocusEvent = 0;
                        }
                    }
                });
                break;
        }
    }

}
